/*  JavaScript File For Zulwi Studying Website(http://study.zhuwei.cc)
*	Author		@JerryLocke
*	Blog		http://jerrys.me
*	Date		2014-03-01
*	Copyright	Zulwi Studio
*	Location	Xintian County of Yongzhou City in Hunan Province
*	The scripts need JavaScript support , please preview in Chrome or other JavaScript-Supported Bowser.
*/
$(".avatarc").click(function(){
	if($("#topDropMenu").css("display")!="block"){
		$(".avatar").css("background-color","#0095bb");
		$("#topDropMenu").slideDown(300);
	}else{
		$("#topDropMenu").slideUp(300);
		$(".avatar").css("background-color","");
	}
	return false;
});

$(".mainBox .box .slider>li").mouseover(function(){
	var p=$(this).attr("p");
	if($(this).attr("class")=="current") return false;
	$(".mainBox .box .slider>li[p="+p+"] .img").animate({width:"0px"}); //li内图片缩小
	$(".mainBox .box .slider>li[p="+p+"]").animate({width:"217px"},300).removeClass("current"); //li整体缩小
	$(this).animate({width:"500px"},200).addClass('current'); //当前li整体变大
	$(".mainBox .box .slider>li[p="+p+"].current .img").animate({width:"217px"}); //当前li内图片变大
});

$(".mainBox .box .slider>li .img .index li").click(function(){
	var p=$(this).parent().parent().parent().attr("p");
	var index=$(this).attr("index");
	var offset=0-index*217;
	if($(this).attr("class")=="current") return false;
	$(this).siblings().removeClass("current");
	for(var i=0;i<=index;i++){
	if(index==0){
		$(".mainBox .box .slider>li[p="+p+"].current .imgShow li").animate({marginLeft:0});
	}else{
		$(".mainBox .box .slider>li[p="+p+"].current .imgShow li[index="+i+"]").animate({marginLeft:offset+i*217});}
	}
	$(this).addClass("current");
	return false;
});

$(".bvtSlider>li").click(function(){
	var p=$(this).parent().attr("p");
	if($(this).attr("class")=="current") {
		$(this).animate({height:"20px"}).removeClass("current");
		return false;
		}
	if($(".bvtSlider[p="+p+"]>li.current").length!=0) $(".bvtSlider[p="+p+"]>li").animate({height:"20px"}).removeClass("current");  //如果有未被缩小的li
	$(this).animate({height:"300px"}).addClass("current");

});

$(".myContent .leftBar .myAvatar").mouseenter(function(){
	$(".myContent .leftBar .myAvatar .change").slideDown(200);
});

$(".myContent .leftBar .myAvatar").mouseleave(function(){
	$(".myContent .leftBar .myAvatar .change").slideUp(200);
});

$("[level1Comment]").click(function(){
	var cid=$(this).parent().attr('cid');
	var parentBox=$(this).parent().parent();
	if(parentBox.children('.sendComment').length==0){
		parentBox.append("<div class='sendComment container' style='border-top:1px dotted #dedede;'><form method='post' onsubmit='return post_form(\"/a/addComment\",this,\"replyTip"+cid+"\");'  onkeydown='if(event.keyCode==13&&event.ctrlKey) $(this).submit();'><div id='replyTip"+cid+"' class='tip' style=\"margin-bottom:2px;\"></div> <textarea name='comment' class='fl' placeholder='在此输入回复...'></textarea><input type='hidden' name='pid' value=\""+cid+"\" /><input type='hidden' name='aid' value=\""+aid+"\" /><input type='submit' class='btn fl' value='回复' /></form></div>");
		parentBox.children('.sendComment').slideDown(300);
		return false;
	}
	parentBox.children('.sendComment').children("[name=\"pid\"]").attr("value",cid);
	parentBox.children('.sendComment').children("[name=\"aid\"]").attr("value",aid);
	if(parentBox.children('.sendComment').css('display')=='block'){
		parentBox.children('.sendComment').slideUp(300);
	}else{
		parentBox.children('.sendComment').slideDown(300);
	}
});

$("[level2Comment]").click(function(){
	var parentBox=$(this).parent().parent().parent().parent().parent().parent();
	var cid=parentBox.children("span.fr[cid]").attr('cid');
	var username=$(this).parent().parent().parent().children("div.name").children('a').html();
	if(parentBox.children('.sendComment').length==0){
		parentBox.append("<div class='sendComment container' style='border-top:1px dotted #dedede;'><form method='post' onsubmit='return post_form(\"/a/addComment\",this,\"replyTip"+cid+"\");'  onkeydown='if(event.keyCode==13&&event.ctrlKey) $(this).submit();'><div id='replyTip"+cid+"' class='tip' style=\"margin-bottom:2px;\"></div> <textarea name='comment' class='fl' placeholder='在此输入回复...'></textarea><input type='hidden' name='pid' value=\""+cid+"\" /><input type='hidden' name='aid' value=\""+aid+"\" /><input type='submit' class='btn fl' value='回复' /></form></div>");
	    parentBox.children('.sendComment').children('form').children('textarea').val('回复 @'+username+' : ');
		parentBox.children('.sendComment').slideDown(300);
		return false;
	}
	parentBox.children('.sendComment').children("[name=\"pid\"]").attr("value",cid);
	parentBox.children('.sendComment').children("[name=\"aid\"]").attr("value",aid);
	parentBox.children('.sendComment').children('form').children('textarea').val('回复 @'+username+' : ');
	if(parentBox.children('.sendComment').css('display')=='block'){
		parentBox.children('.sendComment').slideUp(300);
	}else{
		parentBox.children('.sendComment').slideDown(300);
	}
});

$("[deleteComment]").click(function(){
	var obj=$(this);
	var cid=$(this).parent().attr('cid');
	$.post('/a/delComment','cid='+cid,function(result){
		if(result.status==0){
			location.reload();
		}else{
			alert('删除失败!');
		}
	});
});

$("[deleteMood]").click(function(){
	var obj=$(this);
	var cid=$(this).parent().attr('cid');
	$.post('/i/delMood','cid='+cid,function(result){
		if(result.status==0){
			location.reload();
		}else{
			alert('删除失败!');
		}
	});
});

$("[articleFav]").click(function(){
	var obj=$(this);
	$.post('/a/doFav','aid='+aid,function(result){
		switch(result.status){
			case 0:
				obj.text('已收藏');
				obj.attr('title','点此取消');
				obj.parent().children('span').html(result.data.count);
				break;
			default:
				obj.text('点此收藏');
				obj.attr('title','点此收藏');
				obj.parent().children('span').html(result.data.count);
				break;
		}
	});
});

$("[level1Mood]").click(function(){
	var cid=$(this).parent().attr('cid');
	var parentBox=$(this).parent().parent();
	if(parentBox.children('.sendComment').length==0){
		parentBox.append("<div class='sendComment container' style='border-top:1px dotted #dedede;'><form method='post' onsubmit='return post_form(\"/i/addMood\",this,\"replyTip"+cid+"\");'  onkeydown='if(event.keyCode==13&&event.ctrlKey) $(this).submit();'><div id='replyTip"+cid+"' class='tip' style=\"margin-bottom:2px;width: 409px;\"></div> <textarea name='mood' class='fl' placeholder='在此输入回复...'></textarea><input type='hidden' name='pid' value=\""+cid+"\" /><input type='submit' class='btn fl' value='回复' /></form></div>");
		parentBox.children('.sendComment').slideDown(300);
		return false;
	}
	parentBox.children('.sendComment').children("[name=\"pid\"]").attr("value",cid);
	if(parentBox.children('.sendComment').css('display')=='block'){
		parentBox.children('.sendComment').slideUp(300);
	}else{
		parentBox.children('.sendComment').slideDown(300);
	}
});

$("[level2Mood]").click(function(){
	var parentBox=$(this).parent().parent().parent().parent().parent().parent();
	var cid=parentBox.children("span.fr[cid]").attr('cid');
	var username=$(this).parent().parent().parent().children("div.name").children('a').html();
	if(parentBox.children('.sendComment').length==0){
		parentBox.append("<div class='sendComment container' style='border-top:1px dotted #dedede;'><form method='post' onsubmit='return post_form(\"/i/addMood\",this,\"replyTip"+cid+"\");'  onkeydown='if(event.keyCode==13&&event.ctrlKey) $(this).submit();'><div id='replyTip"+cid+"' class='tip' style=\"margin-bottom:2px;width: 409px;\"></div> <textarea name='mood' class='fl' placeholder='在此输入回复...'></textarea><input type='hidden' name='pid' value=\""+cid+"\" /><input type='submit' class='btn fl' value='回复' /></form></div>");
	    parentBox.children('.sendComment').children('form').children('textarea').val('回复 @'+username+' : ');
		parentBox.children('.sendComment').slideDown(300);
		return false;
	}
	parentBox.children('.sendComment').children("[name=\"pid\"]").attr("value",cid);
	parentBox.children('.sendComment').children('form').children('textarea').val('回复 @'+username+' : ');
	if(parentBox.children('.sendComment').css('display')=='block'){
		parentBox.children('.sendComment').slideUp(300);
	}else{
		parentBox.children('.sendComment').slideDown(300);
	}
});

$(".iCenterMoods [applaud]").click(function(){
	var obj=$(this);
	var cid=$(this).parent().attr('cid');
	$.post('/i/doApplaud','cid='+cid,function(result){
		if(result.status==0){
			obj.html('已赞('+result.data.count+')');
		}else if(result.status==1){
			if(result.data.count) obj.html('您已赞过('+result.data.count+')');
		}else{
			if(result.data.count) obj.html('赞('+result.data.count+')');
		}
	});
});

$(".bookComment [applaud]").click(function(){
	var obj=$(this);
	var cid=$(this).parent().attr('cid');
	$.post('/a/doApplaud','cid='+cid,function(result){
		if(result.status==0){
			obj.html('已赞('+result.data.count+')');
		}else if(result.status==1){
			if(result.data.count) obj.html('您已赞过('+result.data.count+')');
		}else{
			if(result.data.count) obj.html('赞('+result.data.count+')');
		}
	});
});

function post_form(link,obj,tipsid,callback){
	$.post(link, $(obj).serialize(), function(json){
        var result = eval(json);
		if(tipsid){
			$('#'+tipsid).removeClass("error").removeClass("success");
			if(result.status==0){
				$('#'+tipsid).addClass('success').html(result.info);
				$('#'+tipsid).slideDown(500);
			}else{
				$('#'+tipsid).addClass('error').html(result.info);
				$('#'+tipsid).slideDown(500);
			}
			$("#"+tipsid).click(function(){
			$('#'+tipsid).slideUp(500);
			});	
		}
		if(!callback){
			if(result.data.redirect){
				var relay = result.data.relay ? result.data.relay : 2000;
				setTimeout(function(){location.href = result.data.redirect;},relay);
			}else{
				return false;
			}
		}
        return callback(result);
	}, 'json').fail(function() {});
	return false;
}

function showTip(tip,message,status){
	var delay = arguments[3] ? arguments[3] : 500;
	var tipObj = $(tip);
	tipObj.removeClass("error").removeClass("success");
	if(status == 0){
		tipObj.addClass('success').html(message);
		tipObj.slideDown(delay);
	}else{
		tipObj.addClass('error').html(message);
		tipObj.slideDown(delay);
	}
	tipObj.click(function(){
	tipObj.slideUp(delay);
	});	
}

var AvatarUploaded = false;

$("#userPic").uploadify({
	'queueSizeLimit' : 1,
	'removeTimeout' : 0.5,
	'preventCaching' : true,
	'multi'    : false,
	'swf' 			: '/Public/static/js/uploadify-v3.1/uploadify.swf',
	'uploader' 		: '/i/uploadAvatar',
	'buttonText' 	: '<i class="userupIcon"></i>上传头像',
	'width' 		: '200',
	'height' 		: '200',
	'fileTypeExts'	: '*.jpg; *.png; *.gif;',
	'onUploadSuccess' : function(file, data, response){
		var data = $.parseJSON(data);
		if(data['status'] == 1){
			showTip("#uploadAvatarTip",data['info'],1);
			return;
		}
		AvatarUploaded = true;
		var preview = $('.uploadArea').children('#previewHidden');
		preview.show().removeClass('hidden');
		//两个预览窗口赋值
		$('.crop').children('img').attr('src',"/Public/upload/avatar/"+data['data']['savename']);
		//隐藏表单赋值
		$('#imgSrc').val(data['data']);
		//绑定需要裁剪的图片
		var img = $('<img />');
		preview.append(img);
		preview.children('img').attr('src',"/Public/upload/avatar/"+data['data']['savename']);
		var crop_img = preview.children('img');
		crop_img.attr('id',"cropBox").show();
		var img = new Image();
		img.src = "/Public/upload/avatar/"+data['data']['savename'];
		//根据图片大小在画布里居中
		img.onload = function(){
			var img_height = 0;
			var img_width = 0;
			var real_height = img.height;
			var real_width = img.width;
			if(real_height > real_width && real_height > 200){
				var persent = real_height / 200;
				real_height = 200;
				real_width = real_width / persent;
			}else if(real_width > real_height && real_width > 200){
				var persent = real_width / 200;
				real_width = 200;
				real_height = real_height / persent;
			}
			if(real_height < 200){
				img_height = (200 - real_height)/2;	
			}
			if(real_width < 200){
				img_width = (200 - real_width)/2;
			}
			preview.css({width:(200-img_width)+'px',height:(200-img_height)+'px'});
			preview.css({paddingTop:img_height+'px',paddingLeft:img_width+'px'});			
		}
		//裁剪插件
		$('#cropBox').Jcrop({
			bgColor:'#333',   //选区背景色
			bgFade:true,      //选区背景渐显
			fadeTime:1000,    //背景渐显时间
			allowSelect:false, //是否可以选区，
			allowResize:true, //是否可以调整选区大小
			aspectRatio: 1,     //约束比例
			minSize : [100,100],//可选最小大小
			boxWidth : 200,		//画布宽度
			boxHeight : 200,	//画布高度
			onChange: showPreview,//改变时重置预览图
			onSelect: showPreview,//选择时重置预览图
			setSelect:[ 0, 0, 100, 100],//初始化时位置
			onSelect: function (c){	//选择时动态赋值，该值是最终传给程序的参数
				$('#x').val(c.x);//需裁剪的左上角X轴坐标
				$('#y').val(c.y);//需裁剪的左上角Y轴坐标
				$('#w').val(c.w);//需裁剪的宽度
				$('#h').val(c.h);//需裁剪的高度
		  }
		});
		//重新上传,清空裁剪参数
		var i = 0;
		$('.reuploadImg').click(function(){
			showTip("#uploadAvatarTip",'正在删除图片，请稍后...',0);
			$('#previewHidden').find('*').remove();
			$('#previewHidden').hide().addClass('hidden').css({'padding-top':0,'padding-left':0});
		    $.get("/i/delUploadedAvatar", function(result){
			if(result.status==0){
				showTip("#uploadAvatarTip",'删除成功，请重新上传！',0);
			}else{
				showTip("#uploadAvatarTip",'删除失败，请刷新页面！',0);
			}
		    });
		});
	 }
});

//提交裁剪好的图片
$('.savePic').click(function(){
	if($('#previewHidden').html() == ""){
		showTip("#uploadAvatarTip",'请先上传图片！',1);
	}else{
		showTip("#uploadAvatarTip",'图片保存中，请稍后...',0);
		$('#pic').submit();
	}
});

//预览图
function showPreview(coords){
	var img_width = $('#cropBox').width();
	var img_height = $('#cropBox').height();
	  //根据包裹的容器宽高,设置被除数
	  var rx = 100 / coords.w;
	  var ry = 100 / coords.h; 
	  $('#cropPreview100').css({
		width: Math.round(rx * img_width) + 'px',
		height: Math.round(ry * img_height) + 'px',
		marginLeft: '-' + Math.round(rx * coords.x) + 'px',
		marginTop: '-' + Math.round(ry * coords.y) + 'px'
	  });
	  rx = 50 / coords.w;
	  ry = 50 / coords.h;
	  $('#cropPreview50').css({
		width: Math.round(rx * img_width) + 'px',
		height: Math.round(ry * img_height) + 'px',
		marginLeft: '-' + Math.round(rx * coords.x) + 'px',
		marginTop: '-' + Math.round(ry * coords.y) + 'px'
	  });
}